package com.spa.domain.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.spa.domain.entity.UserInfo;
import com.spa.domain.entity.UserTicket;
import com.spa.infrastructure.enums.dict.base.WhetherTypeEnum;
import com.spa.infrastructure.mapper.UserTicketMapperStruct;
import com.spa.infrastructure.repository.condition.TicketCondition;
import com.spa.infrastructure.repository.condition.UserTicketRefCondition;
import com.spa.infrastructure.repository.po.TicketPO;
import com.spa.infrastructure.repository.po.UserTicketRefPO;
import com.spa.infrastructure.repository.service.TicketRepositoryService;
import com.spa.infrastructure.repository.service.UserTicketRefRepositoryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 用户优惠券
 */
@Service
@Slf4j
public class UserTicketService {

    @Resource
    private UserTicketRefRepositoryService userTicketRefRepositoryService;

    @Resource
    private TicketRepositoryService ticketRepositoryService;

    @Resource
    private UserInfoService userInfoService;

    /**
     * 添加用户优惠券
     *
     * @author: lig
     * @date: 2023/12/14
     */
    @Transactional
    public boolean addUserTicket(Integer type, Long userId) {
        //清空用户优惠券
//        userTicketRefRepositoryService.delUserTicketByUserId(userId);
        log.info("addUserTicket : {} {}", type, userId);
        TicketCondition condition = new TicketCondition();
        condition.setType(type);
        List<TicketPO> ticketPoList = ticketRepositoryService.list(condition);
        if (CollUtil.isEmpty(ticketPoList)) return false;
        List<UserTicketRefPO> refPoList = new ArrayList<>();
        ticketPoList.stream().forEach(a -> {
            UserTicketRefPO refPO = BeanUtil.toBean(a,UserTicketRefPO.class);
            refPO.setId(null);
            refPO.setTicketId(a.getId());
            refPO.setUserId(userId);
            refPO.setCreateTime(new Date());
            //开始时间 结束时间计算
            if (a.getComeIntoForceType() == 1) {
                // 将 Date转化为 LocalDateTime 对象
                LocalDateTime localDateTime = DateUtil.toLocalDateTime(refPO.getCreateTime());
                refPO.setBeginDate(refPO.getCreateTime());
                // 将 LocalDateTime转化为 Date 对象
                refPO.setEndDate(new DateTime(localDateTime.plusDays(a.getExpirationDate())));
            }
            refPoList.add(refPO);

            //在添加一套
            UserTicketRefPO refPO2 = BeanUtil.toBean(a,UserTicketRefPO.class);
            refPO2.setId(null);
            refPO2.setTicketId(a.getId());
            refPO2.setUserId(userId);
            refPO2.setCreateTime(new Date());
            //开始时间 结束时间计算
            if (a.getComeIntoForceType() == 1) {
                // 将 Date转化为 LocalDateTime 对象
                LocalDateTime localDateTime = DateUtil.toLocalDateTime(refPO2.getCreateTime());
                refPO2.setBeginDate(refPO2.getCreateTime());
                refPO2.setEndDate(new DateTime(localDateTime.plusDays(a.getExpirationDate())));

            }
            refPoList.add(refPO2);
        });
        return userTicketRefRepositoryService.addBatchUserTicket(refPoList);
    }

    public UserTicket infoUserById(Long id) {
        UserTicketRefPO po = userTicketRefRepositoryService.getUserTicketRefById(id);
        return UserTicketMapperStruct.INSTANCE.po2Entity(po);
    }

    /**
     * 删除关联用户优惠券
     *
     * @author: lig
     * @date: 2023-12-21
     */
    @Transactional
    public boolean delUserTicket(Long ticketId, Long userId) {
        return userTicketRefRepositoryService.updateIsDelById(WhetherTypeEnum.$1.getCode(), ticketId);

    }

    /**
     * 通过用户端用户ID 获取优惠券列表
     *
     * @author: lig
     * @date: 2023-12-22
     */
    public List<UserTicket> listByUserId(Long userId) {
        List<UserTicketRefPO> userTicketRefPONew = new ArrayList<>();
        List<UserTicketRefPO> userTicketRefPO = userTicketRefRepositoryService.getUserTicketRefByUserId(userId);
        if(CollUtil.isNotEmpty(userTicketRefPO)){
            userTicketRefPO.stream().forEach(a ->{
                Date date1 = DateUtil.parse(DateUtil.now());
                if(DateUtil.compare(a.getEndDate(),date1) == -1){
                    //优惠券过期  异步处理
                    updateUserTicketDisabled(a.getId());
                }else {
                    userTicketRefPONew.add(a);
                }
            });
        }
        return UserTicketMapperStruct.INSTANCE.po2Entity4List(userTicketRefPONew);
    }

    public Integer getCouponPrice(Long ticketId) {
        //优惠券金额
        Integer couponPriceInt = 0;
        if (ObjectUtils.isNotEmpty(ticketId)) {
            UserTicket userTicketRef = UserTicketMapperStruct.INSTANCE.po2Entity(userTicketRefRepositoryService.getById(ticketId));
            couponPriceInt = Convert.toInt(userTicketRef.getRmb(), 0);
        }
        return couponPriceInt;
    }

    /**
     * 退还 优惠券给用户
     *
     * @author: lig
     * @date: 2023-12-27
     */
    @Transactional
    public boolean returnUserTicket(Long ticketId) {
        //更新订单状态
        userTicketRefRepositoryService.updateIsDelById(WhetherTypeEnum.$0.getCode(),ticketId);
        return true;
    }

    /**
     * 修改用户优惠券不可用
     *
     * @author: lig
     * @date: 2023/12/28
     */
    @Async
    public boolean updateUserTicketDisabled(Long id){
        return userTicketRefRepositoryService.updateIsDelById(WhetherTypeEnum.$1.getCode(), id);
    }

    public List<UserTicket> listTicketByIds(List<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        UserTicketRefCondition condition = new UserTicketRefCondition();
        condition.setTicketIds(ids);
        List<UserTicketRefPO> userTicketPOList = userTicketRefRepositoryService.list(condition);
        return UserTicketMapperStruct.INSTANCE.po2Entity4List(userTicketPOList);
    }

    public Map<Long, UserTicket> groupById(List<UserTicket> tickets) {
        return tickets.stream().collect(Collectors.toMap(UserTicket::getId, Function.identity()));
    }

    /**
     * 查询用户领取优惠券记录
     * @param condition
     * @return
     */
    public List<UserTicket> list(UserTicketRefCondition condition) {
        List<UserTicket> list =  UserTicketMapperStruct.INSTANCE.po2Entity4List(userTicketRefRepositoryService.list(condition));
        if (CollectionUtil.isNotEmpty(list)){
            List<Long> userIds = list.stream().map(UserTicket::getUserId).toList();
            List<UserInfo> userInfos = userInfoService.getUserListByIds(userIds);
            Map<Long, UserInfo> userInfoMap = userInfos.stream().collect(Collectors.toMap(UserInfo::getId, Function.identity()));
            list.forEach(userTicket -> {
                UserInfo userInfo = userInfoMap.get(userTicket.getUserId());
                if (ObjectUtils.isNotEmpty(userInfo)){
                    userTicket.setUserName(userInfo.getPhone());
                }
            });
        }
        return list;
    }
}
